package org.opencare.ndwc.persistence;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.opencare.ndwc.model.DisasterType;
import org.springframework.dao.DataAccessException;

public class JpaDisasterTypeDao implements DisasterTypeDao {

	@PersistenceContext
    private EntityManager em;
	
	@Override
	public DisasterType find(Long id) throws DataAccessException {
		// TODO Auto-generated method stub
		return em.find(DisasterType.class, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<DisasterType> findAll() throws DataAccessException {
		// TODO Auto-generated method stub
		
		List<DisasterType> result = em.createQuery("select disaster from DisasterType disaster").getResultList();
		
		return result;
	}

	@SuppressWarnings("unchecked")
	@Override
	public DisasterType findDisasterTypeByName(String name)
			throws DataAccessException {
		// TODO Auto-generated method stub
		
		Query ql = em.createQuery("select d from DisasterType d where d.type = :type");
		ql.setParameter("type", name);
		
		return (DisasterType) ql.getSingleResult();
	}
	
	@Override
	public void save(DisasterType disasterType) throws DataAccessException {
		// TODO Auto-generated method stub
		if(disasterType.getId() == null){
			em.persist(disasterType);
		}else{
			em.merge(disasterType);
		}
	}
	
	@Override
	public void remove(Long id) throws DataAccessException {
		// TODO Auto-generated method stub
		DisasterType d = find(id);
		if (d != null) {
			em.remove(d);
		}
	}

	@Override
	public void removeAll() throws DataAccessException {
		// TODO Auto-generated method stub
		em.createQuery ("delete from DisasterType").executeUpdate();
	}

	@Override
	public Long countDisasterType() throws DataAccessException {
		// TODO Auto-generated method stub
		
		Query ql = em.createQuery("select count(d) from DisasterType d");
			
		return (Long) ql.getSingleResult();
	}

}
